package com.example.employ.service.impl;

import cn.hutool.core.bean.BeanUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.employ.common.convention.exception.ClientException;
import com.example.employ.dao.entity.UserDO;
import com.example.employ.dao.mapper.UserMapper;
import com.example.employ.dto.request.UserLoginReqDTO;
import com.example.employ.dto.request.UserRegisterReqDTO;
import com.example.employ.dto.response.UserLoginRespDTO;
import com.example.employ.service.UserService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import static com.example.employ.common.enums.UserErrorCodeEnums.*;


/**
 * @author LYT0905
 * @date 2024/05/23/13:19
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    /**
     * 用户注册
     * @param requestParam 用户注册信息
     */
    @Override
    public void register(UserRegisterReqDTO requestParam) {
        try {
            UserDO userDO = BeanUtil.toBean(requestParam, UserDO.class);
            userDO.setId(null);
            int insert = baseMapper.insert(userDO);
            // 注册失败
            if(insert < 1){
                throw new ClientException(USER_SAVE_ERROR);
            }
            // 主键唯一索引冲突(用户在数据库中已经存在)
        }catch (DuplicateKeyException exception){
            throw new ClientException(USER_EXIST);
        }
    }

    /**
     * 用户登录
     * @param requestParam 用户登录请求参数
     * @return UserLoginRespDTO
     */
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        // MyBatisPlus 用法，去数据库查对应用户信息
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class).
                eq(UserDO::getUsername, requestParam.getUsername()).
                eq(UserDO::getPassword, requestParam.getPassword());
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        // 没找到
        if(userDO == null){
            throw new ClientException(USER_LOGIN_ERROR);
        }
        // 返回用户id
        Long id = userDO.getId();
        return new UserLoginRespDTO(id);
    }
}
